package com.yunxin.admin.system.infra.framework.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yunxin.admin.system.infra.framework.security.userdetails.SysUserDetails;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * mybatis-plus 字段自动填充
 *
 * @link https://mp.baomidou.com/guide/auto-fill-metainfo.html
 * @author zero°
 * @since 2023-05-22
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充创建时间
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "creator", () -> Optional.ofNullable(SecurityUtils.X.getUser()).map(SysUserDetails::getUsername).orElse(""), String.class);
        this.strictUpdateFill(metaObject, "editor", () -> Optional.ofNullable(SecurityUtils.X.getUser()).map(SysUserDetails::getUsername).orElse(""), String.class);

    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "editor",  () -> Optional.ofNullable(SecurityUtils.X.getUser()).map(SysUserDetails::getUsername).orElse(""), String.class);
    }

}
